#include "configRequest.h"
#include "heartRequest.h"
#include "adLogic.h"
gchar *gatewayIp = NULL;
gchar *sn = NULL;
char *getGatewayIp(){
    if (gatewayIp != NULL)
    {
        return gatewayIp;
    }
    //读取当前文件目录下面的config.ini获取devinfo_path地址
    GKeyFile *configiniPath = g_key_file_new();
    if(!g_key_file_load_from_file(configiniPath,"./config.ini",G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return NULL;
    }
    gchar *path = g_key_file_get_string(configiniPath,"config","devinfo_path",NULL);
    g_key_file_free(configiniPath);
    //从devinfo_path指定的文件中读取ip和地址
    GKeyFile *configPath = g_key_file_new();
    if(!g_key_file_load_from_file(configPath,path,G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return NULL;
    }
    gatewayIp = g_key_file_get_string(configPath,"config","gatewayIp",NULL);
    g_key_file_free(configPath);
    return gatewayIp;
}
//缓存sn
gchar *getDiviceSn(){
    // if (sn != NULL)
    // {
    //     return sn;
    // }
    // FILE *file = fopen("/sys/class/dmi/id/product_serial","r");
    // char *sn = (char*)calloc(1,256);
    // //读取数据
    // fgets(sn,256,file);
    // fclose(file);
    // g_print("sn = %s\n",sn);
    return "hahahahahah";
}
void *recvMsgAndSendConfig(void* param){
    while (1)
    {
        printf("wait boa msg:\n");
        int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);
        if (mqId == -1)
        {
            perror("create mq error");
            return NULL;
        }
        Message msg = {
        
        };
        int recvSize = recvMsg(mqId,&msg,MSG_SIZE);
        if (recvSize == -1)
        {
            perror("recv msg error");
        }
        //发送请求
        printf("接收数据成功\n");
        sendConfigRequest();
    }
}
int main(int argc, char const *argv[])
{
    //开一个子线程用来接收mq消息 发送配置信息
    pthread_t tid;
    pthread_create(&tid,NULL,recvMsgAndSendConfig,NULL);
    //每过5秒发一个心跳请求
    while(TRUE){
        g_print("The heartbeat request starts:\n");
        sendHeartRequest(getGatewayIp(),getDiviceSn());
        sleep(30);
        g_print("Sending the heartbeat request is complete!!!\n");
    }
    return 0;
}
